package com.llkj.qingnianguoxue.home;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bigkoo.convenientbanner.holder.CBViewHolderCreator;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.llkj.qingnianguoxue.MainActivity;
import com.llkj.qingnianguoxue.R;
import com.llkj.qingnianguoxue.adapter.HomeBannerAdapter;
import com.llkj.qingnianguoxue.adapter.HomeJXActionAdapter;
import com.llkj.qingnianguoxue.adapter.HomeJXCourseAdapter;
import com.llkj.qingnianguoxue.adapter.HomeJingXuanAdapter;
import com.llkj.qingnianguoxue.adapter.HomeLikeVediosAdapter;
import com.llkj.qingnianguoxue.adapter.HomeModuleAdapter;
import com.llkj.qingnianguoxue.base.BaseFragment;
import com.llkj.qingnianguoxue.base.ConstantUserInfo;
import com.llkj.qingnianguoxue.base.MyApplication;
import com.llkj.qingnianguoxue.bean.AdTipsBean;
import com.llkj.qingnianguoxue.bean.HomeBean;
import com.llkj.qingnianguoxue.bean.HomeLikeBean;
import com.llkj.qingnianguoxue.bean.HomeModuleBean;
import com.llkj.qingnianguoxue.bean.JingXuanBean;
import com.llkj.qingnianguoxue.bean.LunboBean;
import com.llkj.qingnianguoxue.course.BookingAnnouncementActivity;
import com.llkj.qingnianguoxue.course.CourseDetailActivity;
import com.llkj.qingnianguoxue.course.CourseTearcherActivity;
import com.llkj.qingnianguoxue.customview.LooperTextView;
import com.llkj.qingnianguoxue.http.HttpMethod;
import com.llkj.qingnianguoxue.login.LoginActivity;
import com.llkj.qingnianguoxue.mine.ShopCartActivity;
import com.llkj.qingnianguoxue.music.MusicHomeActivity;
import com.llkj.qingnianguoxue.util.DisplayUtil;
import com.llkj.qingnianguoxue.util.GridSpacingItemDecoration;
import com.llkj.qingnianguoxue.util.GsonUtil;
import com.llkj.qingnianguoxue.util.LunBoJumpUtil;
import com.llkj.qingnianguoxue.view.ChatView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.llkj.qingnianguoxue.home.JingXuanActivity.REQUEST_CART_CODE;

/**
 * 首页
 */
public class HomeFragment extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener {
    @BindView(R.id.refresh_layout)
    SwipeRefreshLayout refreshLayout;
    @BindView(R.id.iv_sign)
    ImageView ivSign;//签到
    @BindView(R.id.tv_search)
    TextView tvSearch;//搜索
    @BindView(R.id.ssw_banner)
    ConvenientBanner ssvBanner;//轮播图
    @BindView(R.id.rv_module)
    RecyclerView lvModule;//子功能
    private HomeModuleAdapter moduleAdapter;
    private List<HomeModuleBean> moduleData;
    @BindView(R.id.gv_book)//精选图书
    RecyclerView gvBooks;
    @BindView(R.id.gv_vedio)//精选视频
    RecyclerView gvVedio;
    private HomeJingXuanAdapter jingVedioAdapter, jingBookAdapter;
    private List<JingXuanBean> jingVedioData, jingBookData;
    @BindView(R.id.tv_more)
    TextView tvMore;//查看更多

    @BindView(R.id.gv_like_video)
    RecyclerView gvLikeVedios;//喜欢视频
    private HomeLikeVediosAdapter likeVedioAdapter;
    private List<JingXuanBean> hotVedioData, hotBookData;

    @BindView(R.id.gv_like_book)
    RecyclerView gvLikeBooks;
    private HomeLikeVediosAdapter likeBookAdapter;
    @BindView(R.id.tv_like_book_new)
    TextView tvRefreshBook;//换一批
    private int mVideoSort, mBooksSort;//猜你喜欢分页

    @BindView(R.id.loopertv)
    LooperTextView mLooperTextView;//广告轮播
    @BindView(R.id.gv_course)
    RecyclerView gvCoursse;//课程
    @BindView(R.id.gv_actions)
    RecyclerView gvActions;//活动
    private HomeJXCourseAdapter gvCourseAdapter;
    private HomeJXActionAdapter gvActionAdapter;
    private List<JingXuanBean> mCourseData, mActionData;
    private List<AdTipsBean> mNoticeData;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_home, container, false);
        ButterKnife.bind(this, rootView);

        initView();
        initListener();

        onRefresh();

        return rootView;
    }

    private void initView() {
        refreshLayout.setColorSchemeResources(R.color.blue3989ff);
//        refreshLayout.setProgressViewOffset(false, 0, -200);

        ssvBanner.setFocusable(false);
//        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) ssvBanner.getLayoutParams();
//        params.height = DisplayUtil.getDensityWdith(getActivity()) * 320 / 750;

        //子功能
        initModule();
        lvModule.setLayoutManager(new GridLayoutManager(getActivity(), 4));
        lvModule.addItemDecoration(new GridSpacingItemDecoration(4, 10, false));
        moduleAdapter = new HomeModuleAdapter(R.layout.item_home_module, moduleData);
        lvModule.setAdapter(moduleAdapter);

        //精选视频
        gvVedio.setLayoutManager(new GridLayoutManager(getActivity(), 3));
        gvVedio.addItemDecoration(new GridSpacingItemDecoration(3, 10, false));
        jingVedioData = new ArrayList<>();
        jingVedioAdapter = new HomeJingXuanAdapter(R.layout.item_jing_xuan_vedio2, jingVedioData);
        jingVedioAdapter.setType(1);
        gvVedio.setAdapter(jingVedioAdapter);
        //书籍
        gvBooks.setLayoutManager(new GridLayoutManager(getActivity(), 4));
        gvBooks.addItemDecoration(new GridSpacingItemDecoration(4, 10, false));
        jingBookData = new ArrayList<>();
        jingBookAdapter = new HomeJingXuanAdapter(R.layout.item_jing_xuan_vedio2, jingBookData);
        jingBookAdapter.setType(2);
        gvBooks.setAdapter(jingBookAdapter);

        //课程
        mCourseData = new ArrayList<>();
        gvCoursse.setLayoutManager(new GridLayoutManager(getActivity(), 2));
        gvCoursse.addItemDecoration(new GridSpacingItemDecoration(2, 10, false));
        gvCourseAdapter = new HomeJXCourseAdapter(R.layout.item_jing_xuan_action, mCourseData);
        gvCourseAdapter.setType(1);
        gvCoursse.setAdapter(gvCourseAdapter);

        //活动
        mActionData = new ArrayList<>();
        gvActions.setLayoutManager(new GridLayoutManager(getActivity(), 2));
        gvActions.addItemDecoration(new GridSpacingItemDecoration(2, 10, false));
        gvActionAdapter = new HomeJXActionAdapter(R.layout.item_exchange_action, mActionData);
        gvActionAdapter.setType(2);
        gvActions.setAdapter(gvActionAdapter);

        //喜欢视频
        hotVedioData = new ArrayList<>();
        gvLikeVedios.setLayoutManager(new GridLayoutManager(mActivity, 3));
        gvLikeVedios.addItemDecoration(new GridSpacingItemDecoration(3, 10, false));
        likeVedioAdapter = new HomeLikeVediosAdapter(R.layout.item_jing_xuan_vedio, hotVedioData);
        likeVedioAdapter.setType(2);
        gvLikeVedios.setAdapter(likeVedioAdapter);
        //书籍
        hotBookData = new ArrayList<>();
        gvLikeBooks.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false));
        likeBookAdapter = new HomeLikeVediosAdapter(R.layout.item_jing_xuan_vedio, hotBookData);
        likeBookAdapter.setType(1);
        gvLikeBooks.setAdapter(likeBookAdapter);

        lvModule.setNestedScrollingEnabled(false);
        gvBooks.setNestedScrollingEnabled(false);
        gvVedio.setNestedScrollingEnabled(false);
        gvLikeVedios.setNestedScrollingEnabled(false);
        gvLikeBooks.setNestedScrollingEnabled(false);
    }

    private void initListener() {
        refreshLayout.setOnRefreshListener(this);
        lvModule.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {
                switch (i) {
                    case 0://热门
                        startActivity(HotRankingActivity.class);
                        break;
                    case 1://大师
                        startActivity(MasterActivity.class);
                        break;
                    case 2://范儿视频
                        startActivity(JingXuanActivity.class);
                        break;
                    case 3://范儿书籍
                        startActivity(JingXuanBooksActivity.class);
                        break;
                    case 4://一对一课堂
                        startActivity(CourseTearcherActivity.class);
                        break;
                    case 5://曲库
                        startActivity(MusicHomeActivity.class);
                        break;
                    case 6://活动
                        startActivity(PreviousActionActivity.class);
                        break;
                    case 7://足迹
                        boolean isLogin = MyApplication.getInstance().sputil.getBoolean(ConstantUserInfo.ISLOGIN);
                        if (!isLogin) {
                            dialogConfirm(null, null, null, null).show();
                            return;
                        }
                        startActivity(EveryDayActivity.class);
                        break;
                }
            }
        });
        gvVedio.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {
                JingXuanBean videoBean = jingVedioData.get(i);
                Bundle bundle = new Bundle();
                bundle.putString("id", videoBean.getId());
                startActivity(VideoDetailActivity.class, bundle);
            }
        });
        gvBooks.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {
                JingXuanBean bookBean = jingBookData.get(i);
                Bundle bundle = new Bundle();
                bundle.putString("id", bookBean.getId());
                startActivity(BookDetailActivity.class, bundle);
            }
        });
        gvLikeVedios.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {
                JingXuanBean videoBean = hotVedioData.get(i);
                Bundle bundle = new Bundle();
                bundle.putString("id", videoBean.getId());
                startActivity(VideoDetailActivity.class, bundle);
            }
        });
        gvLikeBooks.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {
                JingXuanBean bookBean = hotBookData.get(i);
                Bundle bundle = new Bundle();
                bundle.putString("id", bookBean.getId());
                startActivity(BookDetailActivity.class, bundle);
            }
        });
        mLooperTextView.setAdClickListener(new LooperTextView.AdCliclListener() {
            @Override
            public void onAdClick(int position) {
                if (position >= 0 && mNoticeData.size() > position) {
                    Bundle bundle = new Bundle();
                    bundle.putString("id", mNoticeData.get(position).getMaster_id());
                    startActivity(BookingAnnouncementActivity.class, bundle);
                }
            }
        });
        gvCoursse.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {
                JingXuanBean item = mCourseData.get(i);
                Bundle bundle = new Bundle();
                bundle.putString("title", item.getName());
                bundle.putString("id", item.getId());
                startActivity(CourseDetailActivity.class, bundle);
            }
        });
        gvActions.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {
                JingXuanBean item = mActionData.get(i);
                Intent intent = new Intent(getActivity(), ActionDetailActivity.class);
                intent.putExtra("from_class", 1);
                intent.putExtra("id", item.getId());
                startActivity(intent);
            }
        });
    }

    /**
     * 轮播图
     *
     * @param list_image
     */
    private void initBanner(final List<LunboBean> list_image) {
        if (list_image == null) {
            return;
        }
        final HomeBannerAdapter bannerAdapter = new HomeBannerAdapter(new HomeBannerAdapter.ClickBannerListener() {

            @Override
            public void clickBanner(int position) {
                LunboBean lunboBean = list_image.get(position);
                //1 活动 2 直播  3 视频 4 图书5讲师 6课程，7伴奏
                String type = lunboBean.getType();
                LunBoJumpUtil.jumpTo(getActivity(), type, lunboBean.getContent_id());
//                if ("1".equals(type)) {
//                    Intent intent = new Intent(getActivity(), ActionDetailActivity.class);
//                    intent.putExtra("id", lunboBean.getContent_id());
//                    startActivity(intent);
//                } else if ("2".equals(type)) {
//                    boolean isLogin = MyApplication.getInstance().sputil.getBoolean(ConstantUserInfo.ISLOGIN);
//                    if (!isLogin) {
//                        dialogConfirm(null, null, null, null).show();
//                        return;
//                    }
//
//                    int state = 0;// state状态1 直播中 2 未开始 3 已结束
//                    try {
//                        state = Integer.parseInt(lunboBean.getState());
//                    } catch (Exception e) {
//                        e.printStackTrace();
//                    }
//                    Bundle bundle = new Bundle();
//                    bundle.putString("id", lunboBean.getContent_id());
//                    switch (state) {
//                        case 2:
//                            startActivity(BookZhiBoActivity.class, bundle);
//                            break;
//                        case 1:
//                            bundle.putString("type", "1");
//                            startActivity(ZhiBoDetailActivity.class, bundle);
//                            break;
//                        case 3:
//                            bundle.putString("type", "2");
//                            startActivity(ZhiBoDetailActivity.class, bundle);
//                            break;
//                    }
//                } else if ("3".equals(type)) {
//                    Bundle bundle = new Bundle();
//                    bundle.putString("id", lunboBean.getContent_id());
//                    startActivity(VideoDetailActivity.class, bundle);
//                } else if ("4".equals(type)) {
//                    Bundle bundle = new Bundle();
//                    bundle.putString("id", lunboBean.getContent_id());
//                    startActivity(BookDetailActivity.class, bundle);
//                }
            }
        });

        ssvBanner.setPages(new CBViewHolderCreator<HomeBannerAdapter>() {
            @Override
            public HomeBannerAdapter createHolder() {
                return bannerAdapter;
            }
        }, list_image)
                .setPageIndicator(new int[]{R.drawable.page_point_normal, R.drawable.page_point_selected})
                .setPageIndicatorAlign(ConvenientBanner.PageIndicatorAlign.CENTER_HORIZONTAL);

    }

    @OnClick({R.id.iv_sign, R.id.tv_search, R.id.tv_more, R.id.tv_like_book_new})
    public void onClick(View v) {
        boolean isLogin = MyApplication.getInstance().sputil.getBoolean(ConstantUserInfo.ISLOGIN);
        switch (v.getId()) {
            case R.id.iv_sign://签到
                if (!isLogin) {
                    dialogConfirm(null, null, null, null).show();
                    return;
                }
                startActivity(SignInActivity.class);
                break;
            case R.id.tv_search://搜索
                startActivity(SearchActivity.class);
                break;
            case R.id.tv_more://更多
                startActivity(HotRankingActivity.class);
                break;
            case R.id.tv_like_book_new://猜你喜歡——书籍
                loadWaitDialog();
                HttpMethod.indexLikeBooks(getActivity(), this, String.valueOf(mBooksSort));
                HttpMethod.indexLikeVideo(getActivity(), this, String.valueOf(mVideoSort));
                break;
        }
    }

    @Override
    protected void dialogRightBtn() {
        super.dialogRightBtn();
        startActivity(LoginActivity.class);
    }

    @Override
    protected void onhttpSuccess(String data, int method) {
        super.onhttpSuccess(data, method);
        refreshLayout.setRefreshing(false);
        if (HttpMethod.HTTP_HOMEPAGE_INDEXLIST == method) {//2.1首页
            HomeBean homeBean = GsonUtil.GsonToBean(data, HomeBean.class);
            if (homeBean != null) {
                boolean isLogin = MyApplication.getInstance().sputil.getBoolean(ConstantUserInfo.ISLOGIN);
                String token = MyApplication.getInstance().sputil.getString(ConstantUserInfo.TOKEN);
//                if (isLogin && !token.equals(homeBean.getToken())) {//需要后台返回token,前端校验，处理其他设备登录情况

                    ((MainActivity) getActivity()).setJPushAlias();
//                }

                initBanner(homeBean.getCarousel());//轮播图设置数据

                try {
                    mNoticeData = new ArrayList<>();
                    mNoticeData.addAll(homeBean.getReserve());
                    mNoticeData.addAll(homeBean.getReserve());
                    mNoticeData.addAll(homeBean.getReserve());
                    mNoticeData.addAll(homeBean.getReserve());
                    mLooperTextView.setTipList(mNoticeData);
                }catch (Exception e){}

                if (homeBean.getVideo() != null) {//精选视频
                    jingVedioData.clear();
                    jingVedioData.addAll(homeBean.getVideo());
                    jingVedioAdapter.notifyDataSetChanged();
                }
                if (homeBean.getBooks() != null) {//精选图书
                    jingBookData.clear();
                    jingBookData.addAll(homeBean.getBooks());
                    jingBookAdapter.notifyDataSetChanged();
                }

                if (homeBean.getRecommend() != null) {//课程
                    mCourseData.clear();
                    mCourseData.addAll(homeBean.getRecommend());
                    gvCourseAdapter.notifyDataSetChanged();
                } else {
                    gvCoursse.setVisibility(View.GONE);
                }

                if (homeBean.getLive() != null) {//活动
                    mActionData.clear();
                    mActionData.addAll(homeBean.getLive());
                    gvActionAdapter.notifyDataSetChanged();
                } else {
                    gvActions.setVisibility(View.GONE);
                }

                if (homeBean.getVideo_like() != null) {//喜欢视频
                    hotVedioData.clear();
                    hotVedioData.addAll(homeBean.getVideo_like());
                    likeVedioAdapter.notifyDataSetChanged();
                }
                if (homeBean.getBooks_like() != null) {//喜欢图书
                    hotBookData.clear();
                    hotBookData.addAll(homeBean.getBooks_like());
                    likeBookAdapter.notifyDataSetChanged();
                }

                mVideoSort = homeBean.getVideo_sort();
                mBooksSort = homeBean.getBooks_sort();
            }
        } else if (HttpMethod.HTTP_INDEX_LIKE_VIDEO == method) {//2.2 猜你喜欢换一换视频
            HomeLikeBean homeLikeBean = GsonUtil.GsonToBean(data, HomeLikeBean.class);
            if (homeLikeBean != null) {

                if (homeLikeBean.getVideo_like() != null) {//喜欢视频
                    hotVedioData.clear();
                    hotVedioData.addAll(homeLikeBean.getVideo_like());
                    likeVedioAdapter.notifyDataSetChanged();
                }
//
                mVideoSort = homeLikeBean.getVideo_sort();
            }
        } else if (HttpMethod.HTTP_INDEX_LIKE_BOOKS == method) {//2.2 猜你喜欢换一换图书
            HomeLikeBean homeLikeBean = GsonUtil.GsonToBean(data, HomeLikeBean.class);
            if (homeLikeBean != null) {
                if (homeLikeBean.getBooks_like() != null) {//喜欢图书
                    hotBookData.clear();
                    hotBookData.addAll(homeLikeBean.getBooks_like());
                    likeBookAdapter.notifyDataSetChanged();
                }

                mBooksSort = homeLikeBean.getBooks_sort();
            }
        }
    }

    @Override
    protected void onhttpFailed(String message, int method) {
        super.onhttpFailed(message, method);
        refreshLayout.setRefreshing(false);
    }

    @Override
    public void onResume() {
        super.onResume();
        ssvBanner.startTurning(5000);
    }

    @Override
    public void onPause() {
        super.onPause();
        ssvBanner.stopTurning();
    }

    @Override
    public void onStop() {
        super.onStop();
    }

    private void initModule() {
        moduleData = new ArrayList<>();
        HomeModuleBean moduleBean = new HomeModuleBean();
        moduleBean.setPic(R.drawable.icon_home_hot);
        moduleBean.setTitle("范儿热门");
        moduleData.add(moduleBean);
        moduleBean = new HomeModuleBean();
        moduleBean.setPic(R.drawable.icon_home_teacher);
        moduleBean.setTitle("范儿导师");
        moduleData.add(moduleBean);
        moduleBean = new HomeModuleBean();
        moduleBean.setPic(R.drawable.icon_home_video);
        moduleBean.setTitle("范儿视频");
        moduleData.add(moduleBean);
        moduleBean = new HomeModuleBean();
        moduleBean.setPic(R.drawable.icon_home_book);
        moduleBean.setTitle("范儿书籍");
        moduleData.add(moduleBean);
        moduleBean = new HomeModuleBean();
        moduleBean.setPic(R.drawable.icon_home_course);
        moduleBean.setTitle("一对一课堂");
        moduleData.add(moduleBean);
        moduleBean = new HomeModuleBean();
        moduleBean.setPic(R.drawable.icon_home_music);
        moduleBean.setTitle("范儿曲库");
        moduleData.add(moduleBean);
        moduleBean = new HomeModuleBean();
        moduleBean.setPic(R.drawable.icon_home_action);
        moduleBean.setTitle("范儿活动");
        moduleData.add(moduleBean);
        moduleBean = new HomeModuleBean();
        moduleBean.setPic(R.drawable.icon_home_foot);
        moduleBean.setTitle("范儿足迹");
        moduleData.add(moduleBean);
    }

    @Override
    public void onRefresh() {
        HttpMethod.indexList(getActivity(), this);
    }

}
